import { get, post, put } from '../utils/request'
import { removeToken } from '../utils/auth'
import router from '../router'
import { ElMessage } from 'element-plus'

// 定义接口返回数据类型
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 用户信息接口
export interface UserInfo {
  id: number
  username: string
  nickname: string
  avatar: string
  roles: string[]
  permissions: string[],
}

// 登录参数接口
export interface LoginParams {
  username: string
  password: string
  rememberMe?: boolean
}


type LoginResult = {
  access_token: string;
  expires_in: number;
  refresh_token: string;
  token_type: string;
}

// 登录接口
export function login(data: LoginParams) {
  return post<LoginResult>('/api/auth/login', data)
}

// 获取用户信息
export function getUserInfo() {
  return get<UserInfo>('/api/user/info')
}

// 退出登录
export function logout() {
  // 使用统一的API前缀，确保走代理
  const logoutUrl = import.meta.env.VITE_LOGOUT_URL?.startsWith('/api') 
    ? import.meta.env.VITE_LOGOUT_URL 
    : `/api${import.meta.env.VITE_LOGOUT_URL || '/auth/logout'}`
  return post(logoutUrl).then(() => {
    removeToken()
    localStorage.removeItem('user_roles')
    localStorage.removeItem('userRole')
    localStorage.removeItem('userMenus')
    localStorage.removeItem('currentUsername')
    ElMessage.success('退出登录成功')
    router.push({
      name: 'Login',
      query: {
        redirect: router.currentRoute.value.fullPath
      }
    })
  })
}

// 修改用户信息
export function updateUserInfo(data: Partial<UserInfo>) {
  return put<ResponseData<UserInfo>>('/api/user/info', data)
}
